package com.example.demo.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.demo.entity.User;
import com.example.demo.entity.UserPreference;
import com.example.demo.mapper.UserMapper;
import com.example.demo.mapper.UserPreferenceMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.Date;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserPreferenceMapper preferenceMapper;
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Override
    public UserPreference getPreference(Integer userId) {
        return preferenceMapper.selectOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserPreference>().eq("user_id", userId));
    }

    @Override
    public Boolean updatePreference(UserPreference preference) {
        return preferenceMapper.updateById(preference) > 0;
    }

    @Override
    public String getAvatarUrl(Integer userId) {
        User user = getById(userId);
        if (user != null && user.getAvatar() != null) {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // 签名有效期 1 小时
            URL url = ossClient.generatePresignedUrl(bucketName, user.getAvatar(), expiration);
            ossClient.shutdown();
            return url.toString();
        }
        return null;
    }
}
